package com.hooper.redisdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooper.redisdemo.domain.Blog;
import com.hooper.redisdemo.domain.User;
import com.hooper.redisdemo.mapper.BlogMapper;
import com.hooper.redisdemo.mapper.UserMapper;
import com.hooper.redisdemo.service.BlogService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.hooper.redisdemo.constant.BlogConstant.BLOG_LIKE_KEY_PREFIX;

/**
 * @author Mind
 * @description 针对表【blog(用户博客表)】的数据库操作Service实现
 * @createDate 2023-02-24 17:42:26
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
        implements BlogService {

    @Resource
    private RedisTemplate<String, Long> redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Override
    public String likeOrNot(Long userId, Long blogId) {
        String key = BLOG_LIKE_KEY_PREFIX + blogId;
        //判断用户是否已经点赞
        //将博客号作为key,userId作为value放入，将当前的时间戳作为score值，值越小排行越前
        Boolean success = redisTemplate.opsForZSet().addIfAbsent(key, userId, System.currentTimeMillis());
        if (Boolean.FALSE.equals(success)) {
            redisTemplate.opsForZSet().remove(key, userId);
            return "已取消点赞！";
        }
        return "已点赞！";
    }

    @Override
    public List<User> topLikeUser(Long blogId) {
        String key = BLOG_LIKE_KEY_PREFIX + blogId;
        //获取前5个用户的id
        Set<Long> top5UserId = redisTemplate.opsForZSet().range(key, 0, 4);
        if (CollectionUtils.isEmpty(top5UserId)) {
            return Collections.emptyList();
        }
        //解决in查询导致排序不能达到预期的效果
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(User::getId, top5UserId)
                .last(String.format("ORDER BY FIELD(id,%s)",
                        Strings.join(top5UserId, ',')));
        return userMapper.selectList(wrapper);
    }
}




